from rest_framework import serializers
from .models import Supplier

class SupplierSerializer(serializers.ModelSerializer):
    class Meta:
        model = Supplier
        fields = ['id', 'name', 'contact', 'phone', 'address', 'status', 'create_time', 'update_time']
        read_only_fields = ['id', 'create_time', 'update_time']

    # def validate_phone(self, value):
    #     if not value.isdigit() or len(value) != 11:
    #         raise serializers.ValidationError('手机号格式不正确')
    #     return value

    def validate_name(self, value):
        if self.instance and self.instance.name == value:
            return value
        if Supplier.objects.filter(name=value).exists():
            raise serializers.ValidationError('供应商名称已存在')
        return value